package cn.itcast.n8;

import lombok.extern.slf4j.Slf4j;

import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * className: TestSchedule
 * description:
 * date: 2023/3/6-10:04
 * <p>
 * project: concurrent
 * package: cn.itcast.n8
 * email: 1085844536@qq.com
 * version:
 *
 * @author WangGuojian
 */
@Slf4j(topic = "c.TestSchedule")
public class TestSchedule {

    /**
     * 如何让每周四 18:00:00 定时执行任务?
     *
     * @param args {@link String[]}
     */
    public static void main(String[] args) {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now);
        // 获取周四时间
        LocalDateTime time = now.withHour(10).withMinute(46).withSecond(0).withNano(0).with(DayOfWeek.MONDAY);
        System.out.println(time);
        // 如果 当前时间 > 本周周四，必须找到下周四
        if (now.isAfter(time)) {
            time = time.plusWeeks(1);
        }
        System.out.println(time);
        // initialDelay 代表当前时间和周四的时间差
        // period 一周的间隔时间
        long period = 1000;
        long initialDelay = Duration.between(now, time).toMillis();
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
        pool.scheduleAtFixedRate(() -> {
            System.out.println("running...");
        }, initialDelay, period, TimeUnit.MILLISECONDS);
    }
}
